﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Customer_Pack : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadDataPack();
            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            txtCreateName.Text = Session["UserName"].ToString();

            //Load shop
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToCombo(cboShop, isShopAll, ProvinceID, ShopID, "");
            txtCreateDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            gvPrmotion.DataSource = new DataTable();
            gvPrmotion.DataBind();
        }
    }

    private void loadDataPack()
    {
        var list = (from l in db.CodeDetails
                    where l.CMCode == "PackType" && l.Status == 'A'
                    && l.CDCode != "1"
                    orderby l.CDCode
                    select new
                    {
                        PackType = l.CDCode,
                        PackTypeDesc = l.CDName
                    }
                   ).ToList();
        gvPack.DataSource = list;
        gvPack.DataBind();

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ViewState["dtPromotion"] = null;
            bool flag = false;
            foreach (GridDataItem it in gvPack.Items)
            {
                string PackType = it["PackType"].Text;
                RadNumericTextBox txtQuantity = (RadNumericTextBox)it.FindControl("txtQuantity");
                int Quantity = int.Parse(txtQuantity.Text == "" ? "0" : txtQuantity.Text);
                if (Quantity > 0)
                {
                    loadPromotion(PackType, Quantity);
                     flag = true;
                }
            }
            if (flag == false)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn số lượng vỏ bao");
                return;
            }
            if (ViewState["dtPromotion"] != null)
            {
                DataTable dtPro = (DataTable)ViewState["dtPromotion"];
                bindingPromotion(dtPro);
            }
            this.gvPack.Enabled = false;
            this.btnSubmit.Enabled = false;
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Pack-btnSubmit_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        using (var transation = new System.Transactions.TransactionScope())
        {
            try
            {
                string shopID = this.cboShop.SelectedValue;

                if (gvPrmotion.Items.Count <= 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Danh sách quà tặng không được trống");
                    return;
                }
                List<CustomerGift> list = new List<CustomerGift>();
                bool flag = false;
                foreach (GridDataItem it in gvPrmotion.Items)
                {
                    string PromotionID = it["PromotionID"].Text;
                    string PromotionDetailID = it["PromotionDetailID"].Text;
                    string ProductID = it["ProductID"].Text;
                    RadNumericTextBox PromotionQuantitySelect = (RadNumericTextBox)it.FindControl("PromotionQuantitySelect");
                    string QuantitySelect = PromotionQuantitySelect.Text;
                    if (int.Parse(QuantitySelect) > 0)
                    {
                        CustomerGift cg = new CustomerGift();
                        cg.ShopID = int.Parse(shopID);
                        cg.ProductID = int.Parse(ProductID);
                        cg.PromotionDetailID = int.Parse(PromotionDetailID);
                        cg.PromotionID = int.Parse(PromotionID);
                        cg.Quantity = int.Parse(QuantitySelect);
                        cg.CreatedBy = Session["UserName"].ToString();
                        cg.LastUpdatedBy = Session["UserName"].ToString();
                        cg.CreatedDateTime = DateTime.Now;
                        cg.LastUpdatedDateTime = DateTime.Now;
                        cg.Status = 'A';
                        list.Add(cg);
                        flag = true;
                    }
                }
                if (flag == false)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng quà tặng");
                    return;
                }
                
                //tru kho
                List<Warehouse> listWarehousePro = new List<Warehouse>();
                var w = (from lw in list group lw by new { lw.ProductID } into g select new { g.Key.ProductID, QtySelectTotal = g.Sum(s => s.Quantity) }).ToList();
                if (w != null)
                {

                    foreach (DataRow dr in w.ToDataTable().Rows)
                    {
                        int ProductID = int.Parse(dr["ProductID"].ToString());
                        int QtySelectTotal = Convert.ToInt32(dr["QtySelectTotal"]);
                        int ShopID = int.Parse(cboShop.SelectedValue);
                        int? a = CheckWarehouse(ProductID, ShopID, QtySelectTotal);
                        if (a != -1)
                        {
                            var ProductName = db.Products.FirstOrDefault<Product>(p => p.ID == ProductID).ProductName;
                            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Quà tặng " + ProductName + " đã hết. Vui lòng chọn quà tặng khác. SL tồn kho: " + a);
                            return;
                        }
                        else
                        {
                            //Tru kho SP Qua tang
                            var Warehouse = db.Warehouses.FirstOrDefault(wa => wa.ProductID == ProductID && wa.Status == 'A' && wa.ShopID == ShopID);
                            Warehouse.Quantity = Warehouse.Quantity - QtySelectTotal;
                            Warehouse.LastUpdatedBy = Session["UserName"].ToString();
                            Warehouse.LastUpdatedDateTime = DateTime.Now;

                            Warehouse.RefCode = "";
                            Warehouse.RefType = "Đổi vỏ bao";
                            Warehouse.Remark = "CustomerGift";

                            listWarehousePro.Add(Warehouse);
                        }
                    }
                }
                db.Update<Warehouse>(listWarehousePro);
                db.Insert<CustomerGift>(list);
                db.SubmitChanges();
                transation.Complete();
                this.btnSave.Enabled = false;
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công!");
            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("Pack-btnSave_Click");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
            }
        }
    }
    private int? CheckWarehouse(int productID, int shopID, decimal Qty)
    {
        int? result = -1;
        try
        {
            if (Qty > 0)
            {
                var wh = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == productID && w.ShopID == shopID);
                if (wh != null)
                {
                    if (wh.Quantity < Qty)
                    {
                        result = wh.Quantity;
                    }
                }
                else
                {
                    result = 0;
                }
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Pack-CheckWarehouse");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return result;
    }
    private void loadPromotion(string packType, int QuantityInput)
    {
        try
        {
            DataTable dtPromotion = getListProductPromotion();
            if (dtPromotion.Rows.Count <= 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng kiểm tra lại chương trình khuyến mãi và chi tiết khuyến mãi theo vỏ bao!");
                return;
            }
            DataTable dtPromotionResult = createDataTablPromotion();
            foreach (DataRow detail in dtPromotion.Select("PackType='" + packType + "'"))
            {
                int PackQuantity = int.Parse(detail["PackQuantity"].ToString());
                int PromotionQuantity = QuantityInput / PackQuantity;

                DataRow drNew = dtPromotionResult.NewRow();
                drNew["ProductID"] = detail["ProductID"];
                drNew["ProductName"] = detail["ProductName"];
                drNew["PromotionDetailID"] = detail["PromotionDetailID"];
                drNew["PackType"] = detail["PackType"];
                drNew["PackTypeDesc"] = detail["PackType"] + " kg";
                drNew["PromotionID"] = detail["PromotionID"];
                drNew["Image"] = detail["Image"];
                drNew["PromotionQuantity"] = PromotionQuantity;
                drNew["PromotionQuantitySelect"] = 0;
                drNew["PackQuantity"] = detail["PackQuantity"].ToString();

                dtPromotionResult.Rows.Add(drNew);
            }
            ViewState["dtPromotion"] = dtPromotionResult;
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Pack-loadPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
            // JavascriptUtil.LoadMessage(UpdatePanel1, false, ex.Message);
        }
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Pack", false);
    }
    protected void PromotionQuantitySelect_TextChanged(object sender, EventArgs e)
    {
        try
        {
            RadNumericTextBox radNumeric = (RadNumericTextBox)sender;
            string QtySelect = radNumeric.Text;
            GridDataItem dataItem = (GridDataItem)radNumeric.NamingContainer;
            string ProductID = dataItem["ProductID"].Text;
            string ProductName = dataItem["ProductName"].Text;
            string PackType = dataItem["PackType"].Text;
            string GvPromotionQuantity = dataItem["PromotionQuantity"].Text;

            

            if (ViewState["dtPromotion"] != null)
            {
                DataTable dtPro = (DataTable)ViewState["dtPromotion"];
                DataRow[] rowArr = dtPro.Select("ProductID='" + ProductID + "' AND PackType='" + PackType + "'");
                if (Convert.ToInt32(QtySelect) < 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được nhỏ hơn 0");
                    radNumeric.Text = "0";
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = "0";
                    return;
                }
                if (rowArr.Count() > 0)
                {
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = QtySelect;
                }

                int totalSelected = Convert.ToInt32(dtPro.AsEnumerable().Where(dr => IntOrNull(dr["PackType"]) == IntOrNull(PackType)).Sum(d => IntOrNull(d["PromotionQuantitySelect"]) * IntOrNull(d["PackQuantity"])));
                int totalQuantyInput = 0;
                foreach (GridDataItem it in gvPack.Items)
                {
                    string PackTypeInput = it["PackType"].Text;
                    if (PackTypeInput == PackType)
                    {
                        RadNumericTextBox QuantityInput = (RadNumericTextBox)it.FindControl("txtQuantity");
                        totalQuantyInput = int.Parse(QuantityInput.Text == "" ? "0" : QuantityInput.Text);
                        break;
                    }
                }
                int totalQuantityRemain = totalQuantyInput - totalSelected;
                if (totalQuantityRemain < 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được vượt quá số lượng khuyến mãi");
                    radNumeric.Text = "0";
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = "0";
                    return;
                }
                int PromotionQuantity = 0;
                foreach (DataRow r in dtPro.Rows)
                {
                    if (IntOrNull(r["PackType"]) == IntOrNull(PackType))
                    {
                        PromotionQuantity = totalQuantityRemain / Convert.ToInt32(r["PackQuantity"]);
                        r["PromotionQuantity"] = PromotionQuantity;
                    }
                }
                ViewState["dtPromotion"] = dtPro;
                bindingPromotion(dtPro);
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Pack-PromotionQuantitySelect_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void bindingPromotion(DataTable dtPro)
    {
        if (dtPro.Rows.Count > 6)
        {
            gvPrmotion.Height = 200;
            gvPrmotion.ClientSettings.Scrolling.AllowScroll = true;
            gvPrmotion.ClientSettings.Scrolling.UseStaticHeaders = true;
        }
        gvPrmotion.DataSource = dtPro;
        gvPrmotion.DataBind();
    }
    private DataTable getListProductPromotion()
    {
        DataTable dt = new DataTable();
        try
        {
            string urlImage = Utils.getUrlImage();
           
                DateTime date = DateTime.Now.Date;
                var listPromotion = (from p in db.Promotions
                                     join pd in db.PromotionDetails on p.ID equals pd.PromotionID
                                     join pro in db.Products on pd.ProductID equals pro.ID
                                     where p.Status == 'A' && pd.Status == 'A' && p.PromotionType == "P"
                                     && pro.Status == 'A' && pro.ProductType == "P"
                                     && date >= p.StartDate && date <= p.EndDate
                                     select new
                                     {
                                         ProductID = pd.ProductID,
                                         PromotionID = pd.PromotionID,
                                         PromotionDetailID = pd.ID,
                                         ProductCode = pro.ProductCode,
                                         ProductName = pro.ProductName,
                                         PackType = pd.PackType,
                                         PackQuantity = pd.PackQuantity,
                                         Image = urlImage + pro.ImagePath
                                     }
                                    ).ToList();
                dt = listPromotion.ToDataTable();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-getListProductPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return dt;
    }
    private DataTable createDataTablPromotion()
    {
        DataTable dt = new DataTable();
        if (ViewState["dtPromotion"] == null)
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("PromotionDetailID");
            dt.Columns.Add("PackTypeDesc");
            dt.Columns.Add("PackType");
            dt.Columns.Add("PromotionID");
            dt.Columns.Add("Image");
            dt.Columns.Add("PromotionQuantity");
            dt.Columns.Add("PromotionQuantitySelect");
            dt.Columns.Add("PackQuantity");
            
        }
        else
        {
            dt = (DataTable)ViewState["dtPromotion"];
        }
        return dt;
    }

    private decimal? DecimalOrNull(object val)
    {
        try
        {
            return Convert.ToDecimal(val);
        }
        catch
        {
            return null;
        }
    }

    private int? IntOrNull(object val)
    {
        try
        {
            return Convert.ToInt32(val);
        }
        catch
        {
            return null;
        }
    }
}